﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Tile;
using TS_XY_Train_Repaire.ToolSystem;

namespace Tool_System_Client
{
    public partial class Tool_List_Form : DevExpress.XtraEditors.XtraForm
    {
        class ItemInfo
        {
            public int iTypeID = 0;
            public string sName = "";
            public int iNormal = 0;
            public int iBorrow = 0;
            public int iDamage = 0;
            public int iLose = 0;
            public string sImage = "";
            public int iToolbox = 0;
        }

        DataTable m_oDataTable = new DataTable();
        Dictionary<int, bool> m_dicToolSelect = new Dictionary<int, bool>();

        public Tool_List_Form()
        {
            InitializeComponent();

            this.WindowState = FormWindowState.Maximized;
            tileView1.OptionsBehavior.AllowSmoothScrolling = true;
        }

        private void Tool_Apply_Form_Load(object sender, EventArgs e)
        {
            InitData();
            SetupView();
        }

        protected virtual void InitData()
        {
            try
            {
                Dictionary<int, ItemInfo> oItemDictionary = new Dictionary<int, ItemInfo>();
                DataTable dt = DBManager.GetInstance().GetToolList();
                foreach (DataRow dataRow in dt.Rows)
                {
                    int iTypeID = int.Parse(dataRow["f_typeid"].ToString());
                    ToolStatus iStatus = (ToolStatus)int.Parse(dataRow["f_statetype"].ToString());

                    if (!oItemDictionary.ContainsKey(iTypeID))
                    {
                        oItemDictionary[iTypeID] = new ItemInfo();
                        oItemDictionary[iTypeID].sName = dataRow["f_tooltypename"].ToString();
                        oItemDictionary[iTypeID].sImage = dataRow["f_picture"].ToString();
                        oItemDictionary[iTypeID].iToolbox = int.Parse(dataRow["f_toolbox"].ToString());
                    }

                    if (iStatus == ToolStatus.Normal)
                        ++oItemDictionary[iTypeID].iNormal;
                    else if (iStatus == ToolStatus.Borrow)
                        ++oItemDictionary[iTypeID].iNormal;
                    else if (iStatus == ToolStatus.Damage)
                        ++oItemDictionary[iTypeID].iDamage;
                    else if (iStatus == ToolStatus.Lose)
                        ++oItemDictionary[iTypeID].iLose;
                }

                m_oDataTable.Columns.Add("f_type", typeof(int));
                m_oDataTable.Columns.Add("f_name", typeof(string));
                m_oDataTable.Columns.Add("f_normal", typeof(string));
                m_oDataTable.Columns.Add("f_borrow", typeof(string));
                m_oDataTable.Columns.Add("f_damage", typeof(string));
                m_oDataTable.Columns.Add("f_lose", typeof(string));
                m_oDataTable.Columns.Add("f_toolboxname", typeof(string));
                m_oDataTable.Columns.Add("Image", typeof(Image));

                foreach (ItemInfo itemInfo in oItemDictionary.Values)
                {
                    DataRow dataRow = m_oDataTable.NewRow();
                    dataRow["f_type"] = itemInfo.iTypeID;
                    dataRow["f_name"] = itemInfo.sName;
                    dataRow["f_normal"] = itemInfo.iNormal;
                    dataRow["f_borrow"] = itemInfo.iBorrow;
                    dataRow["f_damage"] = itemInfo.iDamage;
                    dataRow["f_lose"] = itemInfo.iLose;

                    if (itemInfo.iToolbox != 0)
                        dataRow["f_toolboxname"] = "工具箱";
                    else
                        dataRow["f_toolboxname"] = "工具";

                    try
                    {
                        var img = TS_XY_Train_Repaire.ToolSystem.Utility.ChangeStringToImage(itemInfo.sImage);
                        dataRow["Image"] = new Bitmap(img, new Size(190, 190));
                    }
                    catch { }

                    m_oDataTable.Rows.Add(dataRow);
                }

                gridControl1.DataSource = m_oDataTable;
            }
            catch { }
        }

        void SetupView()
        {
            try
            {
                int Cap2ValAnchor = 0;
                int Item2ItemAnchor = 3;

                // Setup tiles options
                tileView1.BeginUpdate();
                tileView1.OptionsTiles.RowCount = 3;
                tileView1.OptionsTiles.Padding = new Padding(20);
                tileView1.OptionsTiles.ItemPadding = new Padding(10);
                tileView1.OptionsTiles.IndentBetweenItems = 20;
                tileView1.OptionsTiles.ItemSize = new Size(340, 190);
                tileView1.Appearance.ItemNormal.ForeColor = Color.White;
                tileView1.Appearance.ItemNormal.BorderColor = Color.Transparent;
                tileView1.ColumnSet.GroupColumn = tileView1.Columns["f_toolboxname"];
                //Setup tiles template
                TileViewItemElement leftPanel = new TileViewItemElement();
                TileViewItemElement splitLine = new TileViewItemElement();
                TileViewItemElement nameCaption = new TileViewItemElement();
                TileViewItemElement nameValue = new TileViewItemElement();
                TileViewItemElement normalCaption = new TileViewItemElement();
                TileViewItemElement normalValue = new TileViewItemElement();
                TileViewItemElement borrowCaption = new TileViewItemElement();
                TileViewItemElement borrowValue = new TileViewItemElement();
                TileViewItemElement damageCaption = new TileViewItemElement();
                TileViewItemElement damageValue = new TileViewItemElement();
                TileViewItemElement loseCaption = new TileViewItemElement();
                TileViewItemElement loseValue = new TileViewItemElement();
                //TileViewItemElement toolbox = new TileViewItemElement();
                TileViewItemElement image = new TileViewItemElement();
                tileView1.TileTemplate.Add(leftPanel);
                tileView1.TileTemplate.Add(splitLine);
                tileView1.TileTemplate.Add(nameCaption);
                tileView1.TileTemplate.Add(nameValue);
                tileView1.TileTemplate.Add(normalCaption);
                tileView1.TileTemplate.Add(normalValue);
                tileView1.TileTemplate.Add(borrowCaption);
                tileView1.TileTemplate.Add(borrowValue);
                tileView1.TileTemplate.Add(damageCaption);
                tileView1.TileTemplate.Add(damageValue);
                tileView1.TileTemplate.Add(loseCaption);
                tileView1.TileTemplate.Add(loseValue);
                //tileView1.TileTemplate.Add(toolbox);
                tileView1.TileTemplate.Add(image);
                //
                leftPanel.StretchVertical = true;
                leftPanel.Width = 150;
                leftPanel.TextLocation = new Point(-10, 0);
                leftPanel.Appearance.Normal.BackColor = Color.FromArgb(58, 166, 101);
                //
                splitLine.StretchVertical = true;
                splitLine.Width = 3;
                splitLine.TextAlignment = TileItemContentAlignment.Manual;
                splitLine.TextLocation = new Point(140, 0);
                splitLine.Appearance.Normal.BackColor = Color.White;
                //
                nameCaption.Text = "名称";
                nameCaption.TextAlignment = TileItemContentAlignment.TopLeft;
                nameCaption.Appearance.Normal.FontSizeDelta = -1;
                //
                nameValue.Column = tileView1.Columns["f_name"];
                nameValue.AnchorElement = nameCaption;
                nameValue.AnchorIndent = Cap2ValAnchor;
                nameValue.MaxWidth = 150;
                nameValue.Appearance.Normal.FontStyleDelta = FontStyle.Bold;
                nameValue.Appearance.Normal.Font = new Font("Segoe UI Semilight", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                //
                normalCaption.Text = "可借";
                normalCaption.AnchorElement = nameValue;
                normalCaption.AnchorIndent = Item2ItemAnchor * 8;
                normalCaption.Appearance.Normal.FontSizeDelta = -1;
                //
                normalValue.Column = tileView1.Columns["f_normal"];
                normalValue.AnchorElement = normalCaption;
                normalValue.AnchorIndent = Cap2ValAnchor;
                normalValue.Appearance.Normal.FontStyleDelta = FontStyle.Bold;
                normalValue.Appearance.Normal.Font = new Font("Segoe UI Semilight", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                //
                borrowCaption.Text = "已借";
                borrowCaption.AnchorAlignment = DevExpress.Utils.AnchorAlignment.Right;
                borrowCaption.AnchorElement = normalCaption;
                borrowCaption.AnchorIndent = 50;
                borrowCaption.Appearance.Normal.FontSizeDelta = -1;
                //
                borrowValue.Column = tileView1.Columns["f_borrow"];
                borrowValue.AnchorElement = borrowCaption;
                borrowValue.AnchorIndent = Cap2ValAnchor;
                borrowValue.Appearance.Normal.FontStyleDelta = FontStyle.Bold;
                borrowValue.Appearance.Normal.Font = new Font("Segoe UI Semilight", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                //
                damageCaption.Text = "损坏";
                damageCaption.AnchorElement = normalValue;
                damageCaption.AnchorIndent = Item2ItemAnchor;
                damageCaption.Appearance.Normal.FontSizeDelta = -1;
                //
                damageValue.Column = tileView1.Columns["f_damage"];
                damageValue.AnchorElement = damageCaption;
                damageValue.AnchorIndent = Cap2ValAnchor;
                damageValue.Appearance.Normal.FontStyleDelta = FontStyle.Bold;
                damageValue.Appearance.Normal.Font = new Font("Segoe UI Semilight", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                //
                loseCaption.Text = "丢失";
                loseCaption.AnchorAlignment = DevExpress.Utils.AnchorAlignment.Right;
                loseCaption.AnchorElement = damageCaption;
                loseCaption.AnchorIndent = 50;
                loseCaption.Appearance.Normal.FontSizeDelta = -1;
                //
                loseValue.Column = tileView1.Columns["f_lose"];
                loseValue.AnchorElement = loseCaption;
                loseValue.AnchorIndent = Cap2ValAnchor;
                loseValue.Appearance.Normal.FontStyleDelta = FontStyle.Bold;
                loseValue.Appearance.Normal.Font = new Font("Segoe UI Semilight", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                //
                image.Column = tileView1.Columns["Image"];
                image.ImageSize = new Size(190, 190);
                image.ImageAlignment = TileItemContentAlignment.MiddleRight;
                image.ImageScaleMode = TileItemImageScaleMode.ZoomOutside;
                image.ImageLocation = new Point(10, 0);

            }
            finally
            {
                tileView1.EndUpdate();
            }
        }

        Color colorPanel = Color.FromArgb(158, 158, 158);
        Color colorPanelSel = Color.DarkSeaGreen;
        Color colorCaption = Color.FromArgb(219, 219, 219);
        Color colorCaptionSel = Color.FromArgb(193, 222, 204);

        private void tileView1_ItemCustomize(object sender, TileViewItemCustomizeEventArgs e)
        {
            //if (e.Item == null || e.Item.Elements.Count == 0)
            //    return;

            //int id = (int)tileView1.GetRowCellValue(e.RowHandle, tileView1.Columns["f_id"]);
            //UpdateItemStatus(e.Item, m_dicToolSelect[id]);
        }

        private void UpdateItemStatus(TileViewItem tileViewItem, bool bSelect)
        {
            Color panelColor = colorPanel;
            Color captionColor = colorCaption;
            if (bSelect)
            {
                panelColor = colorPanelSel;
                captionColor = colorCaptionSel;
            }

            tileViewItem.Elements[0].Appearance.Normal.BackColor = panelColor;
            tileViewItem.Elements[2].Appearance.Normal.ForeColor = captionColor;
            tileViewItem.Elements[4].Appearance.Normal.ForeColor = captionColor;
            tileViewItem.Elements[6].Appearance.Normal.ForeColor = captionColor;
        }

        private void tileView1_ItemClick(object sender, TileViewItemClickEventArgs e)
        {
            var sColumn = tileView1.Columns["f_id"];
            if (sColumn == null)
                return;

            DataRow dataRow = (DataRow)tileView1.GetDataRow(e.Item.RowHandle);
            if (dataRow == null)
                return;

            int id = int.Parse(dataRow["f_id"].ToString());
            m_dicToolSelect[id] = !m_dicToolSelect[id];
            UpdateItemStatus(e.Item, m_dicToolSelect[id]);
        }

        private void windowsUIButtonPanel1_ButtonClick(object sender, DevExpress.XtraBars.Docking2010.ButtonEventArgs e)
        {
            if (e.Button.Properties.Caption == "返回")
            {
                this.DialogResult = DialogResult.OK;
            }
            else if (e.Button.Properties.Caption == "清空所选")
            {
                InitData();
            }
            else if (e.Button.Properties.Caption == "确认提交")
            {
                ApplyOrder();
            }
        }

        // 提交工单
        private void ApplyOrder()
        {
            List<int> listToolID = new List<int>();

            foreach (KeyValuePair<int, bool> kvp in m_dicToolSelect)
            {
                if (kvp.Value.Equals(true))
                {
                    listToolID.Add(kvp.Key);
                }
            }

            // 修改工具状态
            if (!DBManager.GetInstance().ApplyTools(listToolID))
            {
                MessageBox.Show("修改工具状态失败");
                return;
            }

            // 提交订单
            if (!DBManager.GetInstance().ApplyOrder(DataCache.GetInstance().OUserInfo.SUserCode, DateTime.Now, listToolID))
            {
                MessageBox.Show("提交工单失败!");
                return;
            }

            MessageBox.Show("提交工单成功!");
            this.DialogResult = DialogResult.OK;
        }
    }
}